package projects

import (
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"xpms/app/models"
	"xpms/cores/utils"
)

type ProjectsModule struct {
	Id             int64 `orm:"pk;column(moduleid);" json:"Id,string"`
	Projectid      int64 `json:"Projectid,string"`
	Userid         int64 `json:"Userid,string"`
	Name           string
	Aliasname      string
	Started        int64
	Ended          int64
	Desc           string
	Created        int64
	Status         int
	Projuserid     int64 `json:"Projuserid,string"`
	Produserid     int64 `json:"Produserid,string"`
	Testuserid     int64 `json:"Testuserid,string"`
	Publuserid     int64 `json:"Publuserid,string"`
	Parentmoduleid int64 `json:"Parentmoduleid,string"`
}

func (this *ProjectsModule) TableName() string {
	return models.TableName("projects_module")
}
func init() {
	orm.RegisterModel(new(ProjectsModule))
}

func GetProjectModuleById(id int64) (ProjectsModule, error) {
	var subProject ProjectsModule
	var err error
	o := orm.NewOrm()
	subProject = ProjectsModule{Id: id}
	err = o.Read(&subProject)

	return subProject, err
}
func GetModuleByAliasname(name string, projectid int64) (ProjectsModule, error) {
	var module ProjectsModule
	var err error
	o := orm.NewOrm()
	o.QueryTable(models.TableName("projects_module")).Filter("aliasname", name).Filter("Projectid", projectid).One(&module)
	if err == orm.ErrNoRows {
		return module, nil
	}
	return module, err
}

func AddProjectModule(updPro ProjectsModule) error {
	o := orm.NewOrm()
	pro := new(ProjectsModule)
	pro.Id = updPro.Id
	pro.Projectid = updPro.Projectid
	pro.Userid = updPro.Userid
	pro.Name = updPro.Name
	pro.Aliasname = updPro.Aliasname
	pro.Started = updPro.Started
	pro.Ended = updPro.Ended
	pro.Desc = updPro.Desc
	pro.Created = time.Now().Unix()
	pro.Status = 1
	_, err := o.Insert(pro)
	return err
}
func UpdateProjectModule(id int64, updPro ProjectsModule) error {
	var pro ProjectsModule
	o := orm.NewOrm()
	pro = ProjectsModule{Id: id}

	pro.Name = updPro.Name
	pro.Aliasname = updPro.Aliasname
	pro.Started = updPro.Started
	pro.Ended = updPro.Ended
	pro.Desc = updPro.Desc
	pro.Projuserid = updPro.Projuserid
	pro.Produserid = updPro.Produserid
	pro.Testuserid = updPro.Testuserid
	pro.Publuserid = updPro.Publuserid
	_, err := o.Update(&pro, "name", "aliasname", "started", "ended", "desc", "projuserid", "produserid", "testuserid", "publuserid")
	return err
}

func ModulePageExec(condArr map[string]interface{}, page int, offset int) (ops []ProjectsModuleDto) {
	o := orm.NewOrm()
	var dto []ProjectsModuleDto
	o.Raw(modulePageSql(condArr, 1, page, offset)).QueryRows(&dto)
	return dto
}

func ModulePageCountExec(condArr map[string]interface{}, page int, offset int) int64 {
	o := orm.NewOrm()
	var ProjectsModuleDto int64
	o.Raw(modulePageSql(condArr, 0, page, offset)).QueryRow(&ProjectsModuleDto)
	return ProjectsModuleDto
}

type ProjectsModuleDto struct {
	Id               int64 `json:"Id,string"`
	Projectid        int64 `json:"Projectid,string"`
	Projectname      string
	Userid           int64 `json:"Userid,string"`
	Userrealname     string
	Name             string
	Aliasname        string
	Started          int64
	Ended            int64
	Desc             string
	Created          int64
	Status           int
	Projuserid       int64 `json:"Projuserid,string"`
	Projuserrealname string
	Produserid       int64 `json:"Produserid,string"`
	Produserrealname string
	Testuserid       int64 `json:"Testuserid,string"`
	Testuserrealname string
	Publuserid       int64 `json:"Publuserid,string"`
	Publuserrealname string
}

/**
  组装sql
*/
func modulePageSql(condArr map[string]interface{}, ifsCount, page int, offset int) (string, []interface{}) {
	var sql string
	if ifsCount == 0 {
		sql = sql + `SELECT count(1) FROM (`
	}
	sql = sql + `
	SELECT
      ppm.moduleid id,
	  ppm.*,
	  pp.name AS projectname,
	  up.realname AS userrealname,
	  up1.realname AS testuserrealname,
      up2.realname AS projuserrealname
	FROM  pms_projects pp
	  LEFT JOIN pms_projects_module ppm
		ON ppm.projectid = pp.projectid
	  LEFT JOIN pms_users_profile up ON up.userid=ppm.userid
	  LEFT JOIN pms_users_profile up1 ON up1.userid=ppm.testuserid
      LEFT JOIN pms_users_profile up2 ON up2.userid=ppm.projuserid
	WHERE ppm.status>0 `
	param := make([]interface{}, 0, 0)
	if !utils.IsEmpty(condArr["projectid"]) {
		sql = sql + ` and  pp.projectid=?`
		param = append(param, condArr["projectid"])
	}
	if !utils.IsEmpty(condArr["keyword"]) {
		sql = sql + ` and  ppm.name LIKE concat('%',?,'%')`
		param = append(param, condArr["keyword"])
	}
	if ifsCount == 0 {
		sql = sql + ` ) C`
	} else if ifsCount > 0 {
		if page < 1 {
			page = 1
		}
		if offset < 1 {
			offset, _ = beego.AppConfig.Int("pageoffset")
		}
		start := (page - 1) * offset
		startStr := strconv.Itoa(start)
		offsetStr := strconv.Itoa(offset)
		sql = sql + ` order by ppm.moduleid  LIMIT ` + startStr + `,` + offsetStr
	}
	return sql, param
}
